package com.zhongwang.mms.module.half.service;

import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.HInventory;
import com.zhongwang.mms.module.half.dao.HInventoryDao;
import com.zhongwang.mms.module.half.dao.HProjectInventoryMarkDao;
import com.zhongwang.mms.module.half.model.HProjectInventoryMarkModel;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @description:项目划库存执行
 * @author: th
 * @time: 2020/5/13 15:16
 */
@Service
@Log4j2
public class ProToInvExcService {

    @Autowired
    private HProjectInventoryMarkDao hProjectInventoryMarkDao;
    @Autowired
    private HInventoryDao hInventoryDao;
    @Autowired
    private LogService logService;

    public List<HProjectInventoryMarkModel> list(HProjectInventoryMarkModel query) {

        return hProjectInventoryMarkDao.selectAllApplyByQuery(query);
    }

    /**
     * 执行
     * @param hProjectInventoryMarkModel
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult exec(HProjectInventoryMarkModel hProjectInventoryMarkModel) {
        JsonResult jsonResult = new JsonResult();
        try {
            List<HProjectInventoryMarkModel> projectInventoryMarkModelList = hProjectInventoryMarkDao.findPimAppStatusByPrimaryKeys(hProjectInventoryMarkModel.getPimIds());
            //检测在库数量是否可以执行
            for (HProjectInventoryMarkModel projectInventoryMarkModel : projectInventoryMarkModelList) {
                if (projectInventoryMarkModel.getPimItyType().equals("h")) {
                    HInventory hInventory = hInventoryDao.selectAllById(projectInventoryMarkModel.getPimBeforeItyId());
                    if (hInventory.getItyNum() < projectInventoryMarkModel.getPimNum()) {
                        jsonResult.setType(JsonResult.ResultType.ERROR);
                        jsonResult.setMsg("执行的项目划库存申请中其中物料名称为：【" + hInventory.getItyMatName() + "】的物料因库存数量不符合要求，请驳回该申请！");
                        return jsonResult;
                    }
                }
            }
            //循环执行
            for (HProjectInventoryMarkModel projectInventoryMarkModel : projectInventoryMarkModelList) {
                if (projectInventoryMarkModel.getPimItyType().equals("h")) {
                    HInventory hInventory = hInventoryDao.selectAllById(projectInventoryMarkModel.getPimBeforeItyId());
                    if (hInventory.getItyNum() < projectInventoryMarkModel.getPimNum()) {
                        throw new Exception("执行的项目划库存申请中其中物料名称为：【" + hInventory.getItyMatName() + "】的物料因库存数量不符合要求。");
                    } else {
                        HInventory changeItyNumModel = new HInventory();
                        changeItyNumModel.setItyId(hInventory.getItyId());
                        changeItyNumModel.setItyNum(hInventory.getItyNum() - projectInventoryMarkModel.getPimNum());
                        if(projectInventoryMarkModel.getPimWeight() != null && projectInventoryMarkModel.getPimWeight() != 0){
                            changeItyNumModel.setItyWeight(hInventory.getItyWeight() - projectInventoryMarkModel.getPimWeight());
                        }
                        //更改原库存
                        hInventoryDao.updateByPrimaryKeySelective(changeItyNumModel);
                        hInventory.setItyNum(projectInventoryMarkModel.getPimNum());
                        hInventory.setItyAvaNum(projectInventoryMarkModel.getPimNum());
                        if(projectInventoryMarkModel.getPimWeight() != null && projectInventoryMarkModel.getPimWeight() != 0){
                            hInventory.setItyWeight(projectInventoryMarkModel.getPimWeight());
                            hInventory.setItyAvaWeight(projectInventoryMarkModel.getPimWeight());
                        }
                        hInventory.setItyStockType(1);
                        //插入新库存
                        hInventoryDao.insert(hInventory);
                        HProjectInventoryMarkModel changePimAppStatus = new HProjectInventoryMarkModel();
                        changePimAppStatus.setPimId(projectInventoryMarkModel.getPimId());
                        changePimAppStatus.setPimAppStatus(4);
                        changePimAppStatus.setPimAfterItyId(hInventory.getItyId());
                        changePimAppStatus.setPimExecutorId(ShiroUtils.getUser().getId());
                        changePimAppStatus.setPimExecDate(new Date());
                        //回写项目划库存状态为已执行并标记生成后的新的库存信息，以用于撤销使用。
                        hProjectInventoryMarkDao.updateByPrimaryKeySelective(changePimAppStatus);
                        //记录操作日志
                        logService.saveLog("【成品库】项目化库存执行", "被执行的物料名称：" + hInventory.getItyMatName() + ",所属项目编号：" + hInventory.getItyProCode());
                    }
                }
            }
            //设置返回内容
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("执行成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            //设置返回内容
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("执行失败！");
        }
        return jsonResult;
    }

    /**
     * 驳回
     * @param hProjectInventoryMarkModel
     * @return
     */
    public JsonResult reject(HProjectInventoryMarkModel hProjectInventoryMarkModel) {
        JsonResult jsonResult = new JsonResult();
        try {
            hProjectInventoryMarkModel.setPimAppStatus(2);
            hProjectInventoryMarkDao.updatePimAppStatusByPrimaryKeys(hProjectInventoryMarkModel);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("驳回成功！");
            logService.saveLog("【成品库】项目化库存驳回","被驳回的物料名称" + hProjectInventoryMarkModel.getPimMatDesc());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("驳回失败！");
        }
        return jsonResult;
    }

    /**
     * 撤销
     * @param hProjectInventoryMarkModel
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult revoke(HProjectInventoryMarkModel hProjectInventoryMarkModel) {
        JsonResult jsonResult = new JsonResult();
        try {
            //获取撤销列表
            List<HProjectInventoryMarkModel> projectInventoryMarkModelList = hProjectInventoryMarkDao.findPimAppStatusByPrimaryKeys(hProjectInventoryMarkModel.getPimIds());
            //检测在库数量是否可以撤销
            for (HProjectInventoryMarkModel projectInventoryMarkModel : projectInventoryMarkModelList) {
                //外购件库
                if (projectInventoryMarkModel.getPimItyType().equals("h")) {
                    //获取撤销的库存对象
                    HInventory pInventory = hInventoryDao.selectAllById(projectInventoryMarkModel.getPimAfterItyId());
                    if (pInventory.getItyNum() < projectInventoryMarkModel.getPimNum()) {
                        jsonResult.setType(JsonResult.ResultType.ERROR);
                        jsonResult.setMsg("撤销的项目划库存申请中其中物料名称为：【" + pInventory.getItyMatName() + "】的物料因库存数量不符合要求，不可执行撤销！");
                        return jsonResult;
                    }
                    if (pInventory.getItyAvaNum() < projectInventoryMarkModel.getPimNum()) {
                        jsonResult.setType(JsonResult.ResultType.ERROR);
                        jsonResult.setMsg("撤销的项目划库存申请中其中物料名称为：【" + pInventory.getItyMatName() + "】的物料因可用数量不符合要求，不可执行撤销！");
                        return jsonResult;
                    }
                }
            }
            //循环执行
            for (HProjectInventoryMarkModel projectInventoryMarkModel : projectInventoryMarkModelList) {
                //外购件库
                if (projectInventoryMarkModel.getPimItyType().equals("h")) {
                    //获取撤销的库存对象
                    HInventory hInventory = hInventoryDao.selectAllById(projectInventoryMarkModel.getPimAfterItyId());
                    if (hInventory.getItyNum() < projectInventoryMarkModel.getPimNum()) {
                        throw new Exception("撤销的项目划库存申请中其中物料名称为：【" + hInventory.getItyMatName() + "】的物料因库存数量不符合要求。");
                    }else if (hInventory.getItyAvaNum() < projectInventoryMarkModel.getPimNum()) {
                        throw new Exception("撤销的项目划库存申请中其中物料名称为：【" + hInventory.getItyMatName() + "】的物料因库存数量不符合要求。");
                    }else {
                        //记录操作日志
                        logService.saveLog("【成品库】项目化库存撤销", "被撤销的物料名称：" + hInventory.getItyMatName() + ",所属项目编号：" + hInventory.getItyProCode());
                        //减去因执行新生成的库存数量
                        HInventory changeNumAndAvaNumModel = new HInventory();
                        changeNumAndAvaNumModel.setItyId(hInventory.getItyId());
                        changeNumAndAvaNumModel.setItyNum(hInventory.getItyNum()-projectInventoryMarkModel.getPimNum());
                        changeNumAndAvaNumModel.setItyAvaNum(hInventory.getItyAvaNum()-projectInventoryMarkModel.getPimNum());
                        if(projectInventoryMarkModel.getPimWeight() != null && projectInventoryMarkModel.getPimWeight() != 0){
                            changeNumAndAvaNumModel.setItyWeight(hInventory.getItyWeight() - projectInventoryMarkModel.getPimWeight());
                            changeNumAndAvaNumModel.setItyAvaWeight(hInventory.getItyAvaWeight() - projectInventoryMarkModel.getPimWeight());
                        }
                        //更新因执行新生成的库存数据
                        hInventoryDao.updateByPrimaryKeySelective(changeNumAndAvaNumModel);
                        //增加被执行的库存的数量
                        hInventory= hInventoryDao.selectAllById(projectInventoryMarkModel.getPimBeforeItyId());
                        hInventory.setItyId(hInventory.getItyId());
                        hInventory.setItyNum(hInventory.getItyNum()+projectInventoryMarkModel.getPimNum());
                        //changeNumAndAvaNumModel.setItyAvaNum(hInventory.getItyAvaNum()+projectInventoryMarkModel.getPimNum());
                        if(projectInventoryMarkModel.getPimWeight() != null && projectInventoryMarkModel.getPimWeight() != 0){
                            hInventory.setItyWeight(hInventory.getItyWeight() + projectInventoryMarkModel.getPimWeight());
                            //changeNumAndAvaNumModel.setItyAvaWeight(hInventory.getItyAvaWeight() + projectInventoryMarkModel.getPimWeight());
                        }
                        //反向更新被执行的库存的数量
                        hInventoryDao.updateByPrimaryKeySelective(hInventory);
                        //回写状态
                        HProjectInventoryMarkModel changePimAppStatus = new HProjectInventoryMarkModel();
                        changePimAppStatus.setPimId(projectInventoryMarkModel.getPimId());
                        changePimAppStatus.setPimAppStatus(3);
                        //回写项目划库存状态为未执行。
                        hProjectInventoryMarkDao.updateByPrimaryKeySelective(changePimAppStatus);
                    }
                }
            }
            //设置返回内容
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("撤销成功！");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            //设置返回内容
            jsonResult.setType(JsonResult.ResultType.ERROR);
            jsonResult.setMsg("撤销失败！");
        }
        return jsonResult;
    }
}
